/*
 * Famon (http://code.google.com/p/famon/)
 * Copyright (c) 2010 Carl Crous.
 *
 * This file is part of Famon.
 *
 * Famon is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Famon is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Famon.  If not, see <http://www.gnu.org/licenses/>.
 */

package za.org.foobar.famon.collector;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;


/**
 * @author Carl Crous
 */
public class FileUsageFilter implements Filter {
    private final Log log = LogFactory.getLog(getClass());
    public static List<String> missingFiles = new ArrayList<String>();
    private static final String base = new File("").getAbsolutePath();

    public void init(FilterConfig filterConfig) throws ServletException {
        try {
            FileInputStream fstream = new FileInputStream("UsedFiles.txt");
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = br.readLine()) != null) {
                line = line.trim();
                if (line.length() > 0) {
                    missingFiles.add(line);
                }
            }
            in.close();
        } catch (IOException e) {
            log.error(e);
            return;
        }
     }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {

        String uri = ((HttpServletRequest)req).getRequestURI();
//        log.info("Missing: " + uri);
        if (uri.startsWith("/")) {
            uri = uri.substring(1);
        }
        File f = new File(uri);
//        log.info("Base: " + base);
        if (!f.exists()) {
            String name = f.getAbsolutePath().substring(base.length());
            String prefix = "/famon/sc";
//            log.info("Missing URI: " + uri);
//            log.info("Missing File: " + name);
            if (!missingFiles.contains(name)) {
                name = name.substring(prefix.length() - 3);
                missingFiles.add(name);
            }
            HttpServletResponse response = (HttpServletResponse)res;
            response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
            uri = prefix + "_org/" + uri.substring(prefix.length());
            response.setHeader("Location", uri);
        } else {
            chain.doFilter(req, res);
        }
//        log.info("Path: " + f.getAbsolutePath());
//            File org = new File("d:\\Development\\Java\\famon\\exploded\\org\\", uri);
//            log.info("Org: " + org);
//            if (org.exists()) {
//                ServerUtil.copyFile(org, f);
//                log.info("Copied file");
//            }
//        }

    }

    public void destroy() {
    }
}
